from flask import Flask, render_template, request, redirect, url_for, flash, session
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import check_password_hash, generate_password_hash
from functools import wraps  # 新增导入

app = Flask(__name__)
app.secret_key = 'your_secret_key_here_123456'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:666666@localhost/xdb'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class Login(db.Model):
    __tablename__ = 'flask_register_login'
    id = db.Column(db.Integer, primary_key=True)
    nickname = db.Column(db.String(80), nullable=False)
    password = db.Column(db.String(200))

class UserEmail(db.Model):
    __tablename__ = 'flask_name_email'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), nullable=False)

class UserInfo(db.Model):
    __tablename__ = 'flask_name_addr_phone'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    address = db.Column(db.String(200))
    phone = db.Column(db.String(20))


def login_required(f):
    @wraps(f)  # 关键修改：保留原始函数名
    def decorated_function(*args, **kwargs):
        if not session.get('logged_in'):
            flash('请先登录！', 'warning')
            return redirect(url_for('user_login'))
        return f(*args, **kwargs)
    return decorated_function

@app.route('/login', methods=['GET', 'POST'], endpoint='user_login')
def user_login():
    if request.method == 'POST':
        nickname = request.form['nickname']
        password = request.form['password']
        user = Login.query.filter_by(nickname=nickname).first()

        if user and check_password_hash(user.password, password):
            session['logged_in'] = True
            session['nickname'] = nickname
            flash('登录成功！', 'success')
            return redirect(url_for('index'))
        flash('用户名或密码错误！', 'danger')
    return render_template('login.html')

@app.route('/register', methods=['GET', 'POST'], endpoint='user_register')
def user_register():
    if request.method == 'POST':
        nickname = request.form['nickname']
        password = request.form['password']
        existing_user = Login.query.filter_by(nickname=nickname).first()

        if existing_user:
            flash('用户名已存在！', 'warning')
            return redirect(url_for('user_register'))

        new_user = Login(
            nickname=nickname,
            password=generate_password_hash(password)
        )
        db.session.add(new_user)
        db.session.commit()
        flash('注册成功，请登录！', 'success')
        return redirect(url_for('user_login'))
    return render_template('register.html')

@app.route('/logout', endpoint='user_logout')
def logout():
    session.pop('logged_in', None)
    session.pop('nickname', None)
    flash('您已退出登录！', 'info')
    return redirect(url_for('user_login'))

@app.route('/', endpoint='index')
@login_required
def index():
    users = db.session.query(UserEmail, UserInfo).join(UserInfo, UserEmail.username == UserInfo.username).all()
    return render_template('index.html', users=users)

@app.route('/basic_search', endpoint='basic_search')
def basic_search():
    # 原有查询逻辑保持不变
    search_username = request.args.get('username', '').strip()
    search_email = request.args.get('email', '').strip()
    search_addr = request.args.get('address', '').strip()
    search_phone = request.args.get('phone', '').strip()

    query = db.session.query(UserEmail, UserInfo).join(UserInfo, UserEmail.username == UserInfo.username)

    if search_username:
        query = query.filter(UserEmail.username.like(f"%{search_username}%"))
    if search_email:
        query = query.filter(UserEmail.email.like(f"%{search_email}%"))
    if search_addr:
        query = query.filter(UserInfo.address.like(f"%{search_addr}%"))
    if search_phone:
        query = query.filter(UserInfo.phone.like(f"%{search_phone}%"))

    users = query.all()
    return render_template('index.html', users=users)

@app.route('/add', methods=['POST'], endpoint='add_user')
@login_required
def add_user():
    try:
        username = request.form['username']
        email = request.form['email']
        address = request.form['address']
        phone = request.form['phone']

        new_email = UserEmail(username=username, email=email)
        db.session.add(new_email)

        new_info = UserInfo(username=username, address=address, phone=phone)
        db.session.add(new_info)

        db.session.commit()
    except Exception as e:
        db.session.rollback()
        return f"操作失败: {str(e)}"
    return redirect(url_for('index'))

@app.route('/delete/<int:id>', endpoint='delete_user')
@login_required
def delete_user(id):
    user_email = UserEmail.query.get_or_404(id)
    user_info = UserInfo.query.filter_by(username=user_email.username).first()

    db.session.delete(user_email)
    db.session.delete(user_info)
    db.session.commit()
    return redirect(url_for('index'))

@app.route('/edit/<username>', endpoint='edit_user')
@login_required
def edit_user(username):
    user_email = UserEmail.query.filter_by(username=username).first_or_404()
    user_info = UserInfo.query.filter_by(username=username).first_or_404()
    return render_template('edit_user.html', user=user_email, user_email=user_email, user_info=user_info)

@app.route('/update/<username>', methods=['POST'], endpoint='update_user')
@login_required
def update_user(username):
    new_username = request.form.get('new_username')
    new_email = request.form.get('new_email')
    new_address = request.form.get('new_address')
    new_phone = request.form.get('new_phone')

    user_email = UserEmail.query.filter_by(username=username).first()
    user_email.email = new_email
    user_email.username = new_username  # 如果允许修改用户名

    user_info = UserInfo.query.filter_by(username=username).first()
    user_info.address = new_address
    user_info.phone = new_phone
    user_info.username = new_username  # 如果用户名是外键需要同步更新

    db.session.commit()
    flash('用户信息更新成功！', 'success')
    return redirect(url_for('index'))

@app.route('/search', endpoint='search_user')
@login_required
def search_user():
    keyword = '%' + request.args.get('keyword', '') + '%'
    users = db.session.query(UserEmail, UserInfo).join(UserInfo, UserEmail.username == UserInfo.username).filter(
        UserEmail.username.ilike(keyword) |
        UserEmail.email.ilike(keyword) |
        UserInfo.address.ilike(keyword) |
        UserInfo.phone.ilike(keyword)
    ).all()
    return render_template('index.html', users=users)

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(debug=True)